<template>
  <div
    class="main-input"
    @click="handleOnEdit"
    :class="{ 'main-input--bold': bold }"
  >
    <textarea
      ref="el"
      class="text"
      rows="1"
      :placeholder="hint"
      :style="[fontStyle, { textAlign: align }]"
      @blur="isOnEdit = false"
      v-model="text"
      v-if="isOnEdit"
    />
    <span :style="[fontStyle, { textAlign: align }]" v-else>{{
      text || hint
    }}</span>
  </div>
</template>

<script>
import { ref, watch, nextTick } from "vue";
import throttle from "lodash/throttle";

const calHeight = (el) => {
  el.style.height = "auto";
  el.style.height = `${el.scrollHeight + 1}px`;
};
export default {
  name: "RInput",
  props: {
    modelValue: String,
    hint: String,
    fontStyle: String,
    bold: Boolean,
    align: {
      type: String,
      default: "left",
    },
    autosize: {
      type: Boolean,
      default: true,
    },
  },
  emits: ["update:modelValue"],
  setup(props, ctx) {
    const text = ref(props.modelValue);
    const el = ref(null);
    const isOnEdit = ref(false);
    const throttleCal = throttle(calHeight, 300);
    watch(text, (newVal) => {
      props.autosize && throttleCal(el.value);
      ctx.emit("update:modelValue", newVal);
    });
    watch(
      () => props.modelValue,
      (newVal) => {
        text.value = newVal;
      }
    );
    const handleOnEdit = () => {
      isOnEdit.value = true;
      nextTick(() => {
        throttleCal(el.value);
        el.value.focus();
      });
    };
    return {
      el,
      text,
      isOnEdit,
      handleOnEdit,
    };
  },
};
</script>

<style scoped lang="less">
.main-input {
  width: 100%;
  display: flex;
  align-items: center;

  &--bold {
    font-weight: bold;
  }

  .text {
    resize: none;
    background: none;
    width: 100%;
    height: 100%;
    border: none;
    overflow: hidden;
    color: inherit;
    font: inherit;

    &:focus {
      background: rgba(246, 246, 246, 0.8);
      outline: none;
    }
  }
}
</style>
